<?php

namespace app\controllers;

use app\models\Supplier;
use Yii;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

class SiteController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionGridView()
    {
        $params = $this->request->getQueryParams();
        $page = $this->request->getQueryParam('page', 1);
        $perPage = $this->request->getQueryParam('per_page', 20);

        $supplierQuery = $this->getGridDataQuery($params);

        $dataQueryProvider = new ActiveDataProvider([
            'query' => $supplierQuery,
            'pagination' => [
                'pageSize' => $perPage,
                'page' => $page - 1,
            ],
        ]);

        return $this->render('grid_view', ['datas' => $dataQueryProvider, 'total' => $supplierQuery->count()]);
    }

    public function actionExport()
    {
        return $this->render('grid_export');
    }

    public function actionDoExport()
    {
        $params = $this->request->getQueryParams();

        $supplierQuery = $this->getGridDataQuery($params);


        if(!isset($params['columns']) || empty($params['columns'])){
            return $this->redirect(['export',
                'id' => $params['id'],
                'name' => $params['name'],
                'code' => $params['code'],
                't_status' => $params['t_status'],
                'total' => $params['total'],
            ]);
        }

       $fileName = date('YmdHis').'.csv';

        header("Content-Disposition:attachment;filename=".$fileName);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');

        $columns = $params['columns'];
        $wrstr = join(',', $columns).PHP_EOL;

        $columnsLen = count($columns);
        foreach ($supplierQuery->asArray()->all() as $item) {
            $tempStr = '';
            for ($i = 0; $i < $columnsLen; $i++){
                $tempStr .= $item[$columns[$i]].',';
            }
            $wrstr .= rtrim($tempStr, ',').PHP_EOL;
        }

        echo $wrstr;
    }

    private function getGridDataQuery($params)
    {
        $supplierModel = Supplier::find();
        if(isset($params['id']) && trim($params['id'])){
            $supplierModel->andFilterWhere(['id' => $params['id']]);
        }else{
            if(isset($params['name']) && trim($params['name'])){
                $supplierModel->andFilterWhere(['like', 'name', $params['name']]);
            }
            if(isset($params['code']) && trim($params['code'])){
                $supplierModel->andFilterWhere(['like', 'code', $params['code']]);
            }
            if(isset($params['t_status']) && trim($params['t_status'])){
                $supplierModel->andFilterWhere( ['t_status' => $params['t_status']]);
            }
        }

        return $supplierModel->select('*');
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->actionGridView();
        return $this->render('index');
    }

    /**
     * Login action.
     *
     * @return Response|string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }

        $model->password = '';
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    /**
     * Logout action.
     *
     * @return Response
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return Response|string
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }

    /**
     * Displays about page.
     *
     * @return string
     */
    public function actionAbout()
    {
        return $this->render('about');
    }
}
